﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Granite.Data;
using LeadTracker.DataAccess;
using FormsAuthenticationExtensions;

namespace LeadTrackerMVC
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : HttpApplication
	{
		private static LeadRepository m_LeadRepository;
		private static UserRepository m_UserRepository;
  
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
			);

		}

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);

			var connection = new SqlServerConnection(WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
			m_LeadRepository = new LeadRepository(connection);
			m_UserRepository = new UserRepository(connection);
		}

		public static LeadRepository LeadRepository
		{
			get { return m_LeadRepository; }
		}

		public static UserRepository UserRepository
		{
			get { return m_UserRepository; }
		}

		public static MembershipUser MembershipUser
		{
			get
			{
				var user = (MembershipUser)HttpContext.Current.Session["User"];
				if (user == null)
				{
					user = Membership.GetUser();
					HttpContext.Current.Session["User"] = user;
				}

				return user;
			}
		}

		public static int UserEditorKey
		{
			get {
				//return (int)MembershipUser.ProviderUserKey;

				var ticketData = ((FormsIdentity)HttpContext.Current.User.Identity).Ticket.GetStructuredUserData();
				var key = ticketData["Key"];
				return int.Parse(key);
			}
		}

	}
}

